package middleware

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"maya-service/config"
	"maya-service/constant"
	"maya-service/utils/request"
	"net/http"
)

func ShopAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 商城
		//用户登录终端来源：2、H5(包括微信内部浏览器)；3、Android；4、IOS；6、微信小程序；7、百度小程序；8、支付宝小程序；9、抖音小程序
		tSource := c.GetHeader("Terminal-source")
		if tSource == "6" {
			// token 认证
			token := c.GetHeader("Authorization")
			if token == "" {
				c.JSON(http.StatusUnauthorized, nil)
				c.Abort()
				return
			}

			userData, err := request.GetUserMemberInfo(token, config.Conf.Env)
			if err != nil {
				fmt.Println("GetUserMemberInfo token:", token, "err:", err)
				c.JSON(http.StatusUnauthorized, nil)
				c.Abort()
				return
			}

			if userData == nil || userData.Unionid == "" {
				c.JSON(http.StatusUnauthorized, nil)
				c.Abort()
				return
			}

			ctx := context.WithValue(c.Request.Context(), constant.UserData, userData)
			ctx = context.WithValue(ctx, constant.UserId, userData.Unionid)
			c.Request = c.Request.WithContext(ctx)

			c.Next()
			return
		}

		// 鉴权过程
		token := c.GetHeader("Authorization")
		if token == "" && config.Conf.Env == "prod" {
			c.JSON(http.StatusUnauthorized, nil)
			c.Abort()
			return
		}

		if token != "" {
			storeData, err := request.GetStoreInfo(token, config.Conf.Env)
			if err != nil {
				fmt.Println("GetUserDataByToken token:", token, "err:", err)
				c.JSON(http.StatusUnauthorized, nil)
				c.Abort()
				return
			}

			if storeData.StoreID == 0 {
				c.JSON(401, gin.H{
					"code": 500,
					"data": nil,
					"msg":  "token expired",
				})
				c.Abort()
				return
			}

			ctx := context.WithValue(c.Request.Context(), constant.UserData, storeData)
			ctx = context.WithValue(ctx, constant.UserId, storeData.StoreID)
			c.Request = c.Request.WithContext(ctx)
		}

		c.Next()
	}
}
